package beanstao.util.io;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;

import beanstao.util.Util;

public class StringInputStream extends InputStream
{

	private int cursor;
	private byte[] data;

	public StringInputStream(CharSequence s, String charset)
	{
		if (null != s)
		{
			try
			{
				if (charset == null)
				{
					this.data = s.toString().getBytes();
				}
				else
				{
					this.data = s.toString().getBytes(charset);
				}
			}
			catch (UnsupportedEncodingException e)
			{
				throw Util.wrapThrow(e);
			}
		}
		else
		{
			this.data = new byte[0];
		}
		this.cursor = 0;
	}

	public StringInputStream(CharSequence s)
	{
		this(s, null);
	}

	@Override
	public boolean markSupported()
	{
		return false;
	}

	@Override
	public int read() throws IOException
	{
		if (this.cursor < this.data.length)
		{
			return this.data[this.cursor++];
		}
		return -1;
	}

	@Override
	public int available() throws IOException
	{
		return this.data.length - this.cursor;
	}

	@Override
	public long skip(long n) throws IOException
	{
		long len = 0;
		if ((n > 0) && (this.cursor < this.data.length))
		{
			len = (this.cursor + n);
			if (len > this.data.length)
			{
				len = this.data.length - this.cursor;
				this.cursor = this.data.length;
			}
		}
		else
		{
			len = 0;
		}
		return len;
	}

}
